import 'package:flutter/material.dart';
import 'package:x3_base_core/base_constant/base_icon_data.dart';

// ignore: must_be_immutable
class BaseCustomCheckboxButton extends StatefulWidget {

  /// 是否选中
  final bool checked;

  /// 是否禁用
  final bool disable;

  final Color selectedColor;

  final Function(bool) onChanged;

  ///是否隐藏
  final bool offstage;

  /// 外边距
  double margin;

  BaseCustomCheckboxButton({Key key, this.checked = false, this.disable = false, this.selectedColor, this.onChanged,this.offstage = false}): margin = 8, super(key: key);

  BaseCustomCheckboxButton.tile({Key key, this.checked = false, this.disable = false, this.selectedColor, this.onChanged,this.offstage = false}): margin = 0, super(key: key);

  @override
  _BaseCustomCheckboxButtonState createState() => _BaseCustomCheckboxButtonState();

}

class _BaseCustomCheckboxButtonState extends State<BaseCustomCheckboxButton> {

  /// 选择状态
  bool _checked;

  @override
  void initState() {
    _checked = widget.checked;
    super.initState();
  }

  @override
  void didUpdateWidget(covariant BaseCustomCheckboxButton oldWidget) {
    if (oldWidget.checked != widget.checked) {
      _checked = widget.checked;
    }
    super.didUpdateWidget(oldWidget);
  }

  /// 选中颜色

  Color get _selectedColor => widget.selectedColor ?? Theme.of(context).toggleableActiveColor;
  Color get _checkboxColor => _checked == true ? _selectedColor : Colors.transparent;
  Color get _checkboxBorderColor => _checked == true ? _selectedColor : Color(0xffCCCCCC);

  @override
  Widget build(BuildContext context) {
    return Offstage(
      offstage: widget.offstage,
      child: AbsorbPointer(
        absorbing: widget.disable,
        child: InkWell(
          borderRadius: BorderRadius.all(Radius.circular(20)),
          highlightColor: _selectedColor.withOpacity(0.08),
          splashColor: _selectedColor.withOpacity(0.08),
          onTap: () {
            setState(() {
              _checked = !_checked;
            });
            if (widget.onChanged != null) widget.onChanged(_checked);
          },
          child: Container(
            margin: EdgeInsets.all(widget.margin ?? 0),
            height: 24,
            width: 24,
            alignment: Alignment.center,
            child: _buildContainer(),
          ),
        ),
      ),
    );
  }

  Widget _buildContainer() {
    double size = 18;
    return Center(
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        curve: Curves.ease,
        height: size,
        width: size,
        decoration: BoxDecoration(
          color: _checkboxColor,
          borderRadius: BorderRadius.all(Radius.circular(size)),
          border: Border.all(color: _checkboxBorderColor, width: 1),
        ),
        child: _checked == true ? Icon(BaseIconData.x3Checked, size: 12, color: Colors.white) : SizedBox(),
      ),
    );
  }
}
